package com.example.fbi_text.Acitivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.fbi_text.R;
import com.example.fbi_text.bean.User;
import com.example.fbi_text.database.DBHelper;
import com.example.fbi_text.utils.SpUtils;
import com.example.fbi_text.views.MainActivity;

import java.util.regex.Pattern;

//注册功能
public class RegisterActivity extends AppCompatActivity {

    private EditText etUsernameRegister;
    private EditText etEmailRegister;
    private EditText etPasswordRegister;
    private Button btnRegister;
    private DBHelper dbHelper;
    private SpUtils spUtils;
    private boolean isPasswordVisible = false; // 标记密码是否可见
    private ImageView btnBackToLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化数据库帮助类和SharedPreferences工具类
        dbHelper = DBHelper.getInstance(this);
        spUtils = new SpUtils(this);

        etUsernameRegister = findViewById(R.id.etUsernameRegister);
        etEmailRegister = findViewById(R.id.etEmailRegister);
        etPasswordRegister = findViewById(R.id.etPasswordRegister);
        btnRegister = findViewById(R.id.btnRegister);
        btnBackToLogin = findViewById(R.id.btnBackToLogin);

        // 设置返回按钮的点击事件
        btnBackToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 关闭当前页面，返回登录页面
            }
        });

        // 设置密码图标的点击事件
        etPasswordRegister.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                Drawable drawable = etPasswordRegister.getCompoundDrawables()[2]; // drawableEnd
                if (drawable != null) {
                    // 判断触摸点是否在图标区域内
                    int clickableWidth = drawable.getBounds().width() + etPasswordRegister.getPaddingRight();
                    if (event.getX() >= (etPasswordRegister.getWidth() - clickableWidth)) {
                        togglePasswordVisibility();
                        return true;
                    }
                }
            }
            return false;
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入
                String username = etUsernameRegister.getText().toString().trim();
                String email = etEmailRegister.getText().toString().trim();
                String password = etPasswordRegister.getText().toString().trim();

                // 验证输入是否为空
                if (username.isEmpty() || email.isEmpty() || password.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 验证邮箱格式
                if (!isValidEmail(email)) {
                    Toast.makeText(RegisterActivity.this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 检查用户名是否已存在
                if (dbHelper.isUsernameExists(username)) {
                    Toast.makeText(RegisterActivity.this, "用户名已存在", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 检查邮箱是否已注册
                if (dbHelper.isEmailExists(email)) {
                    Toast.makeText(RegisterActivity.this, "邮箱已被注册", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 创建User对象
                User user = new User();
                user.setUser_name(username);
                user.setUser_email(email);
                user.setUser_password(password);

                // 将用户信息保存到数据库
                long result = dbHelper.insertUser2(user);

                if (result != -1) {
                    // 注册成功后自动登录
                    User registeredUser = dbHelper.login(username, email, password);
                    if (registeredUser != null) {
                        // 保存登录状态和用户信息
                        saveLoginStatus(registeredUser);

                        // 跳转到主页面
                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish(); // 关闭当前注册页面
                    } else {
                        Toast.makeText(RegisterActivity.this, "自动登录失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 注册失败
                    Toast.makeText(RegisterActivity.this, "注册失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 切换密码可见性
    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPasswordRegister.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            etPasswordRegister.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_visibility_off, 0);
        } else {
            // 显示密码
            etPasswordRegister.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            etPasswordRegister.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_visibility, 0);
        }
        isPasswordVisible = !isPasswordVisible;
        // 移动光标到末尾
        etPasswordRegister.setSelection(etPasswordRegister.getText().length());
    }

    // 邮箱格式验证方法
    private boolean isValidEmail(String email) {
        if (email == null || email.isEmpty()) {
            return false;
        }
        //正则表达式验证
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +
                "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }


    // 保存用户登录状态和信息
    private void saveLoginStatus(User user) {
        spUtils.putInt(SpUtils.LOGIN_KEY, user.getUser_id()); // 使用LOGIN_KEY常量
        spUtils.putString("username", user.getUser_name());
        spUtils.putString("email", user.getUser_email());
        spUtils.putBoolean("is_logged_in", true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}